#!/usr/bin/python
# -*- coding: utf-8 -*-


from pylot.core import (Path, mkdtempu, check_type, Collection, Plugin)

class PluginError(Exception): pass

def check_plugin (plugin_path, io, tr_=tr_):
  FATAL_ERRORS = []
  WARNINGS = []
  path = Path(plugin_path)
  assert(path.isdir())
  plugin_name = path.name

  # FILES AND DIRECTORIES
  io.write(tr_(u'*** check paths\n'))
  if not Path(path, u'handler.py').isfile() :
    FATAL_ERRORS.append(_('handler.py file is missing'))
  for file in (u'cli.py', u'gui.py') :
    if not Path(path, file).isfile() :
      WARNINGS.append(tr_(u'Optional file %(FILE)s is missing, it may be an error') % dict(FILE=file))
  if not Path(path, u'i18n').isdir() :
    WARNINGS.append(tr_(u'"i18n" translation directory is missing') % dict(FILE=file))
  if Path(path, u'gui.py').isfile() and not Path(path, u'icons').isdir() :
    WARNINGS.append(tr_(u'Optional directory "icons" is missing') % dict(FILE=file))
  if list(path.walkfiles(u'*.ui')) :
    if not Path(path, u'code.pro').isfile():
      FATAL_ERRORS.append(_('code.pro is required for designer file (*.ui) translation'))

  # CODE
  io.write(tr_(u'*** check handler.py\n'))
  plugin = Plugin(path.name)
  tmpdir = mkdtempu()

  io.write(tr_(u' - check read/write settings\n'))
  handler = plugin.handler_class()

  try: options = handler._options
  except AttributeError : pass
  else :
    check_type(u'HandlerPart._options', options, Collection)

  try :
    handler.writeSettings(tmpdir, None)
    handler.writeSettings()
  except TypeError :
    pass
  else :
    FATAL_ERRORS.append(tr_(u'%(METHOD)s method must accept exactly %(N)d arguments') % dict(
      METHOD=u'HandlerPart.writeSettings', N=2))

  try :
    handler.writeSettings(tmpdir)
  except TypeError :
    FATAL_ERRORS.append(tr_(u'%(METHOD)s method must accept exactly %(N)d arguments') % dict(
      METHOD=u'HandlerPart.writeSettings', N=2))

#  handler.writeSettings(tmpdir)
#  handler.readSettings(tmpdir)

  tmpdir.rmtree()

  # SUMMARY
  io.writeStderr(tr_(u'Summary'), style=u'title')
  io.writeStderr(tr_(u'Number of fatal errors : %d\n' % len(FATAL_ERRORS)))
  io.writeStderr(tr_(u'Number of warnings : %d\n' % len(WARNINGS)))
  for error in FATAL_ERRORS :
    io.writeStderr(u'%s\n' % error, style=u'warn')
  for error in WARNINGS :
    io.writeStderr(u'%s\n' % error, style=u'info')
